package com.jshoperxms.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import com.jshoperxms.controller.mall.backstage.vo.OrderCreateProcessInfoVo;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.enums.CartEnums;
import com.jshoperxms.controller.utils.enums.OrderEnums;
import com.jshoperxms.controller.utils.maths.Arith;
import com.jshoperxms.controller.utils.statickey.SerialKeys;
import com.jshoperxms.dao.*;
import com.jshoperxms.entity.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.service.OrderTService;

@Service("orderTService")
@Scope("prototype")
public class OrderTServiceImpl extends BaseTServiceImpl<OrderT>implements OrderTService {
	@Resource
	private OrderTDao orderTDao;
	@Resource
	private Serial serial;
	@Resource
	private OrderShippingAddressTDao orderShippingAddressTDao;
	@Resource
	private MemberCartTDao memberCartTDao;
	@Resource
	private OrderInvoiceTDao orderInvoiceTDao;
	@Resource
	private MemberDeliverAddressTDao memberDeliverAddressTDao;
	@Resource
	private PaymentTDao paymentTDao;
	@Resource
	private LogisticsBusinessTDao logisticsBusinessTDao;
	@Resource
	private OrderProductSnapshotTDao orderProductSnapshotTDao;
	@Resource
	private MemberInvoiceTDao memberInvoiceTDao;

	/**
	 * 通过后台添加订单信息
	 * @param memberCartTs
	 * @param memberT
	 * @param memberDeliverAddressId
	 * @param logisticsid
	 * @param paymentid
	 * @param memberinvoiceid
	 * @param customerordernotes
	 * @param shouldpay
     * @param freight
     * @return
     */
	@Transactional(isolation = Isolation.SERIALIZABLE,propagation=Propagation.REQUIRED)
	@Override
	public OrderCreateProcessInfoVo createBackOrderTranscational(List<MemberCartT> memberCartTs, MemberT memberT, String memberDeliverAddressId, String logisticsid, String paymentid, String memberinvoiceid, String customerordernotes, double shouldpay, double freight) {

		OrderCreateProcessInfoVo op=new OrderCreateProcessInfoVo();

		//1,生成订单号
		String orderid=this.serial.Serialid(SerialKeys.ORDER);
		op.setOrderid(orderid);//设置订单id
		//生成同一批次购物id
		String samecartbatchid=this.serial.Serialid(SerialKeys.MEMBERCARTBATCH);
		op.setSamecartbatchid(samecartbatchid);//同一批次购物id
		op.setShouldpay(shouldpay);//设置应支付款项
		op.setFreight(freight);//设置运费
		op.setMemberinvoiceid(memberinvoiceid);//开票信息id
		op.setMainimg(memberCartTs.get(0).getMainimg());
		op.setSmainimg(memberCartTs.get(0).getSmainimg());
		op.setOrdername(memberCartTs.get(0).getProductname()+"...");
		//2,查询会员地址信息
		MemberDeliverAddressT mda=this.memberDeliverAddressTDao.findByPK(MemberDeliverAddressT.class,memberDeliverAddressId);
		if(mda!=null){
			op.setMemberdeliveraddressid(mda.getId());//设置会员的收获地址id
			//3,添加发货地址信息
			OrderShippingAddressT osa=new OrderShippingAddressT();
			osa.setId(this.serial.Serialid(SerialKeys.ORDERSHIPPINGADDRESS));
			osa.setCity(mda.getCity());
			osa.setCountry(mda.getCountry());
			osa.setCreatetime(DateTools.getSystemTimeBi());
			osa.setDeliveraddressid(mda.getId());
			osa.setDetail(mda.getDetail());
			osa.setDistrict(mda.getDistrict());
			osa.setEmail(mda.getEmail());
			osa.setIssend(OrderEnums.ShippingIsSend.SHIPPING_UNSEND.getState());
			osa.setMemberid(mda.getMemberid());
			osa.setMobile(mda.getMobile());
			osa.setOrderid(op.getOrderid());
			osa.setPostcode(mda.getPostcode());
			osa.setProvince(mda.getProvince());
			osa.setShippingstatus(OrderEnums.ShippingInOrder.SHIPPING_BIND_ORDER.getState());
			osa.setShippingusername(mda.getConsignee());
			osa.setStatus(BaseEnums.DataUsingState.USING.getState());
			osa.setStoreid(StaticKey.EMPTY);
			osa.setStreet(mda.getStreet());
			osa.setTelno(mda.getTelno());
			osa.setUpdatetime(DateTools.getSystemTimeBi());
			osa.setVersiont(1);
			this.orderShippingAddressTDao.save(osa);
			op.setSaveOrderShippingAddress(true);//设置已经设定了发货地址
			op.setOrdershippingaddressid(osa.getId());//设置发货地址id
			op.setOrdershippingusername(osa.getShippingusername());//设置收获人名称
		}

		//4,查询支付方式
		PaymentT pm=this.paymentTDao.findByPK(PaymentT.class,paymentid);
		if(pm!=null){
			op.setPaymentid(pm.getId());//设置了支付方式id
			op.setPayCode(pm.getCode());//设置了支付方式代码
			op.setPaymentname(pm.getName());//设置了支付方式名称
		}

		//5,查询物流商信息
		LogisticsBusinessT logisticsBusinessT=this.logisticsBusinessTDao.findByPK(LogisticsBusinessT.class,logisticsid);
		if(logisticsBusinessT!=null){
			op.setLogisticsid(logisticsBusinessT.getId());//设置物流商id
			op.setLogisticsname(logisticsBusinessT.getLogisticsname());//设置物流商的名称
			op.setLogisticswebaddress(logisticsBusinessT.getWebsite());//设置物流商查询状态地址
		}

		//6,保存订单快照和更新同一批次订单
		for(MemberCartT p:memberCartTs){
			//更新同一批次购物id
			p.setRporderid(op.getOrderid());
			p.setSamecartbatchid(op.getSamecartbatchid());
			p.setCartstatus(CartEnums.CartStatus.HAVE_RPTOORDER_THREE_NUM.getState());
			this.memberCartTDao.update(p);
			//保存订单快照
			OrderProductSnapshotT ops=new OrderProductSnapshotT();
			ops.setId(this.serial.Serialid(SerialKeys.ORDERPRODUCTSNAPSHOTT));
			ops.setAddtime(DateTools.getSystemTimeBi());
			ops.setBasicuserid(BaseTools.getAdminCreateId());
			ops.setBasicusername(BaseTools.getAdminCreateName());
			ops.setCartactiontag(CartEnums.CartActionTag.SYSSEND_EIGHT_NUM.getState());
			ops.setCartstatus(CartEnums.CartStatus.NEWADDTOCART_BACKSTAGE_ZERO_NUM.getState());
			ops.setCarttag(StaticKey.EMPTY);
			ops.setChangeprice(BigDecimal.valueOf(Arith.sub(p.getSaleprice().doubleValue(),p.getMemberprice().doubleValue())));
			ops.setCreatetime(DateTools.getSystemTimeBi());
			ops.setGoodsid(p.getGoodsid());
			ops.setHtmlpath(p.getHtmlpath());
			if(StringUtils.equals(p.getStoreid(),StaticKey.EMPTY)){
				ops.setIsmall(CartEnums.IsMall.SELF.getState());
			}else{
				ops.setIsmall(CartEnums.IsMall.STORE.getState());
			}
			ops.setIswishlist(CartEnums.IsWishList.NO.getState());
			ops.setMainimg(p.getMainimg());
			ops.setMemberid(memberT.getId());
			ops.setMembername(memberT.getLoginname());
			ops.setMemberprice(p.getMemberprice());
			//查询购物车中这个会员的这个货物的购买数量
			ops.setNeedquantity(p.getNeedquantity());
			ops.setPoints(p.getPoints());
			ops.setProductid(p.getProductid());
			ops.setProductname(p.getProductname());
			ops.setPromotioncometag(CartEnums.PromotionComeTag.SYSSEND_EIGHT_NUM.getState());
			ops.setPsn(p.getPsn());
			ops.setRporderid(op.getOrderid());
			ops.setSaleprice(p.getSaleprice());
			ops.setSamebatchid(p.getSamecartbatchid());
			ops.setSmainimg(p.getSmainimg());
			ops.setStatus(BaseEnums.DataUsingState.USING.getState());
			ops.setStockstatus(p.getStockstatus());
			ops.setStoreid(p.getStoreid());
			ops.setStorename(p.getStorename());
			ops.setSubtotal(p.getSubtotal());
			ops.setUpdatetime(DateTools.getSystemTimeBi());
			ops.setVersiont(1);
			ops.setWeight(p.getWeight());
			ops.setWeightunit(p.getWeightunit());
			ops.setPskuvals(p.getPskuvals());
			op.setNeedquantity(op.getNeedquantity()+p.getNeedquantity());//设置订单商品总数
			this.orderProductSnapshotTDao.save(ops);
			op.setSaveOrderProductSnapshot(true);
		}
		//7,保存订单
		OrderT orderT=new OrderT();
		orderT.setOrderid(op.getOrderid());
		orderT.setAmount(BigDecimal.valueOf(op.getShouldpay()));
		orderT.setBasicuserid(BaseTools.getAdminCreateId());
		orderT.setBasicusername(BaseTools.getAdminCreateName());
		orderT.setCreatetime(DateTools.getSystemTimeBi());
		orderT.setCustomerordernotes(customerordernotes);
		orderT.setDeliveraddressid(op.getMemberdeliveraddressid());
		orderT.setDelivermode(OrderEnums.OrderDeliverMode.ORDERDELIVERMODE_EXPRESS.getState());
		orderT.setDeliverynumber(StaticKey.EMPTY);//发货单号空
		orderT.setDeliverytime(null);
		orderT.setErrorordertag(StaticKey.EMPTY);
		orderT.setExpressnumber(StaticKey.EMPTY);//快递单号
		orderT.setFreight(BigDecimal.valueOf(op.getFreight()));
		orderT.setGetpoints(BigDecimal.valueOf(0.0));//后台增加的订单积分为0
		orderT.setIscustomerdelivertime(OrderEnums.OrderCustomerDeliverTime.NO.getState());
		if(StringUtils.equals(op.getMemberinvoiceid(),StaticKey.EMPTY)) {
			orderT.setIsneedinvoice(OrderEnums.IsneedInvoice.NO.getState());
		}else{
			orderT.setIsneedinvoice(OrderEnums.IsneedInvoice.YES.getState());
		}
		orderT.setIsprintexpress(OrderEnums.PrintExpressStatus.EXPRESS_NOT_PRINT_ZERO_NUM.getState());
		orderT.setIsprintfpinvoice(OrderEnums.PrintFaPiaoInvoiceStatus.FAPIAOINVOICE_NOT_PRINT_ZERO_NUM.getState());
		orderT.setIsprintinvoice(OrderEnums.PrintInvoiceStatus.INVOICE_NOT_PRINT_ZERO_NUM.getState());
		orderT.setLogisticsid(op.getLogisticsid());
		orderT.setLogisticsname(op.getLogisticsname());
		orderT.setLogisticssite(op.getLogisticswebaddress());
		orderT.setMainimg(op.getMainimg());
		orderT.setMemberdelivertime(null);//没有自定义发货时间
		orderT.setMemberid(memberT.getId());
		orderT.setMembername(memberT.getLoginname());
		orderT.setNeedquantity(op.getNeedquantity());
		orderT.setOrdername(op.getOrdername());
		orderT.setOrderstatus(OrderEnums.OrderStatus.ORDERSTATE_CONFIRMED_ONE_NUM.getState());
		orderT.setOrdertag(OrderEnums.OrderCreateTag.ORDERTAG_NORMAL_ONE_NUM.getState());//普通订单
		orderT.setPaymentid(op.getPaymentid());
		orderT.setPaymentname(op.getPaymentname());
		orderT.setPaystatus(OrderEnums.OrderPayState.ORDERPAYSTATE_UNPAY_ZERO_NUM
				.getState());
		orderT.setPaytime(null);
		orderT.setPurchasetime(null);
		orderT.setShippingaddressid(op.getOrdershippingaddressid());
		orderT.setShippingstatus(OrderEnums.OrderShippingState.ORDERSHIPPINGSTATE_UNDELIVER_GOODS_ZERO_NUM
				.getState());
		orderT.setShippingusername(op.getOrdershippingusername());
		orderT.setShouldpay(BigDecimal.valueOf(op.getShouldpay()));
		orderT.setSmainimg(op.getSmainimg());
		orderT.setStoreid(StaticKey.EMPTY);//表示平台
		orderT.setStorename(StaticKey.EMPTY);
		orderT.setTobuyernote(StaticKey.EMPTY);
		orderT.setTradenumber(StaticKey.EMPTY);
		orderT.setUpdatetime(DateTools.getSystemTimeBi());
		orderT.setUsepoints(BigDecimal.valueOf(0.0));//后台不适用积分
		orderT.setVersiont(1);
		orderT.setStatus(BaseEnums.DataUsingState.USING.getState());
		this.orderTDao.save(orderT);
		op.setSaveOrder(true);

		//8,保存开票信息
		if(!StringUtils.equals(op.getMemberinvoiceid(),StaticKey.EMPTY)) {
			MemberInvoiceT mi=this.memberInvoiceTDao.findByPK(MemberInvoiceT.class,op.getMemberinvoiceid());
			if(mi!=null){
				OrderInvoiceT oi=new OrderInvoiceT();
				oi.setId(this.serial.Serialid(SerialKeys.ORDERINVOICE));
				oi.setAmount(BigDecimal.valueOf(op.getShouldpay()));
				oi.setBankaddress(mi.getBankaddress());
				oi.setBankname(mi.getBankname());
				oi.setCompanyname(mi.getCompanyname());
				oi.setCreatetime(DateTools.getSystemTimeBi());
				oi.setInvcontent(StaticKey.EMPTY);
				oi.setInvoicestatus(OrderEnums.PrintFaPiaoInvoiceStatus.FAPIAOINVOICE_NOT_PRINT_ZERO_NUM.getState());
				oi.setInvtitle(mi.getInvtitle());
				oi.setInvtype(mi.getInvtype());
				oi.setMemberid(mi.getMemberid());
				oi.setMobile(memberT.getMobile());
				oi.setOrderid(op.getOrderid());
				oi.setStatus(BaseEnums.DataUsingState.USING.getState());
				oi.setStoreid(StaticKey.EMPTY);//表示平台,如果开票的也要考虑不同店铺的形式
				oi.setTaxnumber(mi.getTaxnumber());
				oi.setUpdatetime(DateTools.getSystemTimeBi());
				oi.setVersiont(1);
				this.orderInvoiceTDao.save(oi);
			}
		}
		return op;
	}

}
